// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
Cypress.Commands.add('login', (username, password) => {
  // 添加调试日志
  cy.log(`Attempting to login as ${username}`)
  
  // 根据用户名判断是否为管理员登录
  const isAdmin = username === 'admin'
  const loginPath = isAdmin ? '/admin/login' : '/user/login'
  
  // 访问对应的登录页面
  cy.log(`Visiting ${loginPath}`)
  cy.visit(loginPath)
  
  // 等待页面加载完成
  cy.get('.login-container', { timeout: 15000 }).should('be.visible').then(() => {
    cy.log('Login page loaded')
  })
  
  // 输入用户名和密码
  cy.get('input[placeholder*="用户名"]')
    .should('be.visible')
    .clear()
    .type(username, { delay: 100 })
    .should('have.value', username)
  
  cy.get('input[placeholder*="密码"]')
    .should('be.visible')
    .clear()
    .type(password, { delay: 100 })
    .should('have.value', password)
  
  // 点击登录按钮，使用更精确的选择器
  cy.get('button.el-button--primary')
    .contains('登录')
    .should('be.visible')
    .click()
  
  // 验证登录成功并跳转到对应页面
  if (isAdmin) {
    cy.url({ timeout: 15000 }).should('include', '/admin')
    cy.log('Waiting for admin container')
    cy.get('.admin-container', { timeout: 20000 }).should('be.visible')
  } else {
    cy.url({ timeout: 15000 }).should('include', '/user/home')
    cy.log('Waiting for user home page')
    cy.get('.book-card', { timeout: 20000 }).should('be.visible')
  }
  
  cy.log('Login completed successfully')
})

//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })